export function rect(ctx: CanvasRenderingContext2D, x: number, y: number, w: number, h: number, r: number) {
    if (w < 2 * r) { r = w / 2; }
    if (h < 2 * r) { r = h / 2; }
    ctx.beginPath();
    ctx.moveTo(x + r, y);
    ctx.arcTo(x + w, y, x + w, y + h, r);
    ctx.arcTo(x + w, y + h, x, y + h, r);
    ctx.arcTo(x, y + h, x, y, r);
    ctx.arcTo(x, y, x + w, y, r);
    ctx.closePath();
}

export function ImageLoader(src: string): Promise<[null|string,HTMLImageElement]> {
    return new Promise(resolve => {
        let img = new Image();
        img.src = src;
        img.onload = () => {
            // @ts-ignore
            resolve([null, img]);
        }
        img.onerror = () => {
            // @ts-ignore
            resolve(['error', img]);
        }
    });
}

export function drawImage(ctx: CanvasRenderingContext2D ,position: TCoord, size: TSize, img: HTMLImageElement) {
    const imageW = img.width;
    const imageH = img.height;
    let sourceRectMinW = imageW > imageH ? imageH : imageW;
    let targetRectMaxW = size.w > size.h ? size.w : size.h;
    const multiple = targetRectMaxW / sourceRectMinW;

    const drawImageSize = { w: imageW * multiple, h: imageH * multiple };
    const drawPosition = {
        x: position.x - (drawImageSize.w - size.w) / 2,
        y: position.y - (drawImageSize.h - size.h) / 2
    };
    ctx.drawImage(img, drawPosition.x, drawPosition.y, drawImageSize.w, drawImageSize.h);
}